package com.gold.zookeeperdemo.lock;

import org.I0Itec.zkclient.IZkDataListener;
import org.I0Itec.zkclient.ZkClient;
import org.I0Itec.zkclient.exception.ZkNodeExistsException;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;

/**
 *      zk分布式锁-保持独占：创建节点成功则获得锁
 *      @author yf
 */
public class ZkLock implements Lock{
    /**
     * 创建一个zk客户端
     */
    private ZkClient zkclient=new ZkClient("47.97.23.184:2181");
    {
        zkclient.setZkSerializer(new MyZkSerializer());
    }
    private static final String LOCK_PATH="/LOCK";

    /**
     * 获取锁，所有要同步的线程，创建同名的节点
     *      如果创建成功，则获得锁
     *      如果创建失败，则阻塞自己，等待锁释放
     * @return
     */
    @Override
    public boolean tryLock() {
        try{
            //创建一个持久节点LOCK_PATH
            zkclient.createPersistent(LOCK_PATH);
            return true;
        }catch (ZkNodeExistsException e){
            return false;
        }
    }

    @Override
    public void lock() {
        if(!tryLock()){
            waitForLock();
            lock();
        }
    }
    private void waitForLock(){
        //阻塞自己
        CountDownLatch latch=new CountDownLatch(1);
        //注册一个watcher，监听锁节点事件
        IZkDataListener listener=new IZkDataListener() {
            @Override
            public void handleDataChange(String s, Object o) throws Exception {

            }
            @Override
            public void handleDataDeleted(String s) throws Exception {
                //收到节点删除的通知，就唤醒等待的线程
                latch.countDown();
                System.out.println("---------收到节点删除通知-----------");
            }
        };
        //订阅：监听LOCK_PATH的状态
        zkclient.subscribeDataChanges(LOCK_PATH,listener);

        //阻塞自己，等待锁释放
        if(zkclient.exists(LOCK_PATH)){
            try {
                //此处阻塞，等待countDown()唤醒
                latch.await();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        //移除订阅：接收到删除通知后，就不需要监听此节点了，先移除此订阅。若再次进入此方法，开头会再次注册监听
        zkclient.unsubscribeDataChanges(LOCK_PATH,listener);
    }
    @Override
    public void unlock() {
        zkclient.delete(LOCK_PATH);
    }


    @Override
    public void lockInterruptibly() throws InterruptedException {

    }



    @Override
    public boolean tryLock(long time, TimeUnit unit) throws InterruptedException {
        return false;
    }



    @Override
    public Condition newCondition() {
        return null;
    }
}
